var MongoDB = require('mongodb').Db;
var Server = require('mongodb').Server;
var moment = require('moment');


/*
 ESTABLISH DATABASE CONNECTION
 */

var dbName = process.env.DB_NAME || 'node-login';
var dbHost = process.env.DB_HOST || 'localhost';
var dbPort = process.env.DB_PORT || 27017;

var db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
db.open(function (e, d) {
    if (e) {
        console.log(e);
    } else {
        if (process.env.NODE_ENV == 'live') {
            db.authenticate(process.env.DB_USER, process.env.DB_PASS, function (e, res) {
                if (e) {
                    console.log('mongo :: error: not authenticated', e);
                }
                else {
                    console.log('mongo :: authenticated and connected to database :: "' + dbName + '"');
                }
            });
        } else {
            console.log('mongo :: connected to database :: "' + dbName + '"');
        }
    }
});

var reservations = db.collection('reservations');


//添加或者更新预约信息  type: 1-查看 2-更新 3-添加
exports.updateReservation = function (newData, type, callback) {
    console.log('--------updateReservation---------');
    var result = {};
    //如果是更新预约信息， 检查是否有该预约
    if (type == 2) {
        reservations.count({'id': newData['id']}, function (err, count) {
            if (count > 0) {//如果有
                reservations.update({"id": newData.id}, {$set: newData}, function (err, res) {
                    console.log('update --- err' + err);
                    if (err) {
                        result['id'] = 2;
                        result['msg'] = "预约信息更新失败";
                        callback(result);
                    } else {
                        result['id'] = 1;
                        result['msg'] = "预约信息更新成功";
                        callback(result);
                    }
                });
            } else { //更新失败
                result['id'] = 2;
                result['msg'] = "预约信息更新失败";
                callback(result);
            }
        });
    } else { //添加新预约
        reservations.update({"id": newData.id}, {$set: newData}, {upsert: true}, function (err, res) {
            console.log('update --- err' + err);
            if (err) {
                result['id'] = 2;
                if (newData['status'] == 2) { //管理员或者特殊用户
                    result['msg'] = "预约失败";
                } else { //普通用户
                    result['msg'] = "预约申请失败";
                }
                callback(result);
            } else {
                result['id'] = 1;
                if (newData['status'] == 2) { //管理员或者特殊用户
                    result['msg'] = "预约成功";
                } else { //普通用户
                    result['msg'] = "预约申请成功, 请等待管理员审核";
                }
                callback(result);
            }
        });
    }


};


//检查预约是否存在
function isReservationExists(findQuery, callback) {
    console.log(' --- isReservationExists ---');

    reservations.count(findQuery, function (err, count) {
        console.log("err: " + err);
        console.log("count: " + count);
        var res = {};
        if (count > 0) {//如果有   1 - 重复提交 2 - 提交失败
            res['id'] = 4;
            res['msg'] = "预约已存在, 不要重复提交";
            callback(res);
        } else {
            res['id'] = 0;
            res['msg'] = "预约不存在";
            callback(res);
        }
    });

}

//更新预约状态
exports.updateReservationStatus = function (updateData, callback) {
    console.log(' --- updateReservationStatus ---');
    var res = {};
    reservations.update({"id": updateData.id}, {$set: {'status': updateData.status}}, function (err, result) {
        if (err) {
            res['id'] = 2;
            if (callback)
                callback(res);
        } else {
            res['id'] = 1;
            if (callback)
                callback(res);
        }
    });
};

//检查预约时间段是否与该会议室已有的时间冲突
exports.checkRoomReservation = function (findQuery, callback) {
    console.log(' --- findRoomReservation ---');
    var roomId = findQuery['room_id'];
    var start = findQuery['start'];
    var end = findQuery['end'];
    var user = findQuery['user'];
    var type = findQuery['type'];  //1-查看 2-更新 3-添加
    var role = findQuery['role']; //用户角色，1 管理员 2 普通用户 3-特殊用户
    //查找是否当前用户已经提交， 避免重复
    isReservationExists({'user': user, 'start': start, 'end': end}, function (result) {
        if (result.id == 0) { //不存在
            reservations.find({
                $or: [
                    {'room_id': roomId, 'start': {$lte: start}, 'end': {$gte: start}},
                    {'room_id': roomId, 'start': {$lte: end}, 'end': {$gte: end}},
                    // {'room_id': roomId, 'start': {$lte: start}, 'end': {$lte: end}},
                    {'room_id': roomId, 'start': {$gte: start}, 'end': {$lte: end}},
                ]
            }).toArray(function (err, res) {
                console.log("find err: " + err);
                console.log("res.length: " + res.length);
                if (res.length == 0) { //没有时间冲突
                    result['id'] = 1;
                    result['msg'] = '没有时间冲突';
                    callback(result);
                } else {
                    var isConflit = false;
                    for (var i = 0; i < res.length; i++) {
                        var status = Number(res[i]['status']);
                        if (status == 2) { //如果申请已经成功
                            if (type === 2) { //如果是更新
                                console.log(' --- user user --- ', user, ' , ', res[i]['user']);
                                if (user === res[i]['user']);
                                {
                                    isConflit = false;
                                }
                            } else {//如果是添加
                                isConflit = true;
                                break;
                            }
                        }
                    }

                    if (isConflit) { //如果冲突
                        result['id'] = 3;
                        result['msg'] = '申请失败,\n请选更换申请时间, 该时间段已有成功的预约。';
                        callback(result);
                    } else {//如果可能冲突
                        if (type == 2) { //如果是更新，不提示可能失败
                            result['id'] = 1;
                            callback(result);
                        } else { //添加
                            if (role === 2) { //如果是普通用户
                                result['id'] = 2;  //可能有时间冲突
                                result['msg'] = '申请可能失败，\n因为该时间已有其他预约申请，选择继续申请或者修改时间。';
                                callback(result);
                            } else { //如果是管理员或者特殊用户
                                result['id'] = 1;
                                callback(result);
                            }
                        }
                    }
                }
            });
        } else { //预约已存在
            callback(result);
        }
    });


};


//删除预约
exports.deleteReservation = function (data, callback) {

    var result = {};
    reservations.remove({'id': data.id}, function (err, res) {
        console.log('remove err ' + err);
        console.log('remove res ' + res);
        if (err) {
            result['id'] = 2;
            result['msg'] = '删除失败';
        } else {
            result['id'] = 1;
            result['msg'] = '删除成功';
        }
        callback(result);
    });

};

//按会议室查找预约列表
exports.getAllReservations = function (query, callback) {
    var result = {};
    reservations.find(query).toArray(function (e, res) {
            console.log(' all reservations ---- err   ' + e);
            if (e) { //失败
                result['id'] = 2;
                result['data'] = null;
            } else {
                result['id'] = 1;
                result['data'] = res;
            }
            callback(result)
        }
    );
};

//查询一个预约
exports.getOneReservation = function (query, callback) {
    console.log("query :", query);
    var result = {};
    reservations.findOne(query, function (e, res) {
        if (e) {
            result['id'] = 2;
            result['data'] = null;
        } else {
            result['id'] = 1;
            result['data'] = res;
        }
        callback(result);
    });
};

//admin operate database
exports.delRecord = function (newData, callback) {
    reservations.findOne({id: newData.id}, function (e, o) {
        if (o) {
            reservations.remove({id: newData.id}, callback);
        } else {
            callback(true, null);
        }
    })
};

exports.delAllRecords = function (callback) {
    reservations.remove({}, callback);
};


/* private encryption & validation methods */
